package org.akomantoso.core.data;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.akomantoso.core.data.attribute.Source;
import org.akomantoso.core.io.Externalizable;
import org.akomantoso.core.io.Input;
import org.akomantoso.core.io.InputConstants;
import org.akomantoso.core.io.Output;
import org.akomantoso.core.io.OutputUtil;

/**
 * 
 * <pre>
 *  <xsd:element name="notes">
 * 		<xsd:complexType>
 * 			<xsd:sequence minOccurs="1" maxOccurs="unbounded">
 * 				<xsd:element ref="note"/>
 *  			</xsd:sequence>
 * 			<xsd:attributeGroup ref="source"/>
 * 		</xsd:complexType>
 * 	</xsd:element>
 * </pre>
 * 
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 * 
 * @since http://www.akomantoso.org/1.0
 * 
 */
public final class Notes implements org.akomantoso.core.data.attribute.Source, Externalizable {

	public static final String ELEMENT = "notes";

	// Mandatory (min 1)
	private List<Note> _notes = new ArrayList<Note>(4);

	// Mandatory
	private String _source;

	/**
	 * @see org.akomantoso.core.data.attribute.Source#getSource()
	 */
	@Override
	public String getSource() {
		return _source;
	}

	/**
	 * )
	 * 
	 * @see org.akomantoso.core.data.attribute.Source#setSource(java.lang.String)
	 */
	@Override
	public void setSource(String source) {
		_source = source;
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#writeExternal(org.akomantoso.core.io.Output)
	 */
	@Override
	public <T extends Output> void writeExternal(T out) throws IOException {
		out.writeStart(ELEMENT);
		OutputUtil.writeSource(out, this);
		for (int i = 0, n = _notes.size(); i < n; i++) {
			_notes.get(i).writeExternal(out);
		}
		out.writeEnd();
	}

	/**
	 * @see org.akomantoso.core.io.Externalizable#readExternal(org.akomantoso.core.io.Input)
	 */
	@Override
	public <T extends Input> void readExternal(T in) throws IOException {
		_source = in.readAttribute(Source.ATTRIBUTE);
		Note note;
		while (true) {
			in.readNext();
			switch (in.getEventType()) {
			case InputConstants.START_ELEMENT:
				_notes.add(note = new Note());
				note.readExternal(in);
				break;
			case InputConstants.END_ELEMENT:
				if (Notes.ELEMENT.equals(in.getLocalName())) {
					return;
				}
			}
		}
	}

}